<template>
    <div class="locate" v-if="isHome">
        <div class="njsx_logo" style="width:2.4rem">
            <img src="static/image/ning_logo.png" style="width: 100%;"/>
        </div>
        <div id="allmap" style="display:none;">
		</div>
        <div class="midPart">
            <p @click="goChoose" v-show="!locationInfo && !ScopeOutInfo" style="display: flex;align-items: center;justify-content: space-between;">
                <i class="icon njfont nj-dizhi locatePic" :style="{'margin-left':(showLocateFailed ? .2 : 0) + 'rem'}"></i>
                <img v-show='!showLocateFailed' src="static/image/homeLoading.gif" style="width: .7rem;">
                <span v-show='!showLocateFailed' style="display: inline-block;width: 60%;text-align:left;">定位中...</span>
                <span v-show='showLocateFailed' style="display: inline-block;width: 65%;text-align:left;">定位失败</span>
            </p>
            <p @click="goChoose" v-if="locationInfo || ScopeOutInfo"><i class="icon njfont nj-dizhi" style="font-size: .8rem"></i>{{locationInfo ? locationInfo.address : ScopeOutInfo.address}}</p>
            <div @click="showPop" style="width: 20%;display: flex;align-items:center;justify-content:center;">
                <img src="static/image/index-arrow.png" class="arrow" style="width: .6rem;height: .4rem;">
            </div>
        </div>
        <div @click="toSeach" class="toSeach">
			<i class="icon njfont nj-sousuo" style="font-size: 1.25rem;color:#444; opacity:0.7; line-height:3.3rem"></i>
		</div>
    </div>
</template>
<script>
import axios from 'axios';
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex';
import {Toast} from "../../utils/toast";
export default {
    props:{
        isHome:{
            type: Boolean,
            default: false,
        }
    },
    data() {
        return{
            locateSpot: "",
            stores: [],
            minDistanceItem: {},
            defaultStore: "",
            polygonList: [],
            storeCode: '',
            showLocateFailed: false
        }
    },
    computed:{
        ...mapGetters('qxz',{
            locationInfo: 'getLocation',
            ScopeOutInfo: 'getScopeOut',
            getStoreList: 'getStoreList'
        }),
        ...mapGetters('zx',[
            "getIsShow"
        ]),
        zxPageHeight(){
            return window.environment === "edit" ? 600 : window.screen.height;
        },
        zxPageWidth(){
            return window.environment === "edit" ? 375 : window.screen.width;
        },
    },
    mounted(){
        localStorage.getItem('locateIn') && this.$store.dispatch('qxz/updateLocation', JSON.parse(localStorage.getItem('locateIn')));
        localStorage.getItem('locateOut') && this.$store.dispatch('qxz/updateScopeOut', JSON.parse(localStorage.getItem('locateOut')));
        this.isHome && !this.locationInfo && !this.ScopeOutInfo && this.initScript();
        this.isHome && !this.getStoreList.length && this.getStores();
    },
    methods:{
        ...mapMutations('zx',[
            "setIsShow"
        ]),
        getPos(){
            let Pos = JSON.parse(localStorage.getItem("currentPos"));
            return Pos;
        },
        getPosition(){

        },
        toSeach(){
            this.$router.push("searcher");
        },
        goChoose(){
            this.$router.push("chooseAddress");
        },
        //展示遮罩层
		appendCover(){
			var myPopup = document.querySelector('.nav_root');
			if(!document.getElementById('zxHomeCover')){
                var node = document.createElement('div');
                var RecStore = document.createElement("div");
                var sendTo = document.createElement("p");
                var locate = document.createElement("p");
                var store = document.createElement("p");
                sendTo.innerHTML = '送至：';
                locate.innerHTML = this.locationInfo ? this.locationInfo.address : '不在配送范围内';
                store.innerHTML = `门店：${localStorage.getItem('storeName') || '暂无'}`;
				let nodeStyle = `opacity: 0;display: none;position: absolute;left: 0;top:3rem;z-index:1;touch-action: none;width:${this.zxPageWidth}px;height:${this.zxPageHeight}px;background: black;`;
                let RecStyle = 'width:100%;height:2.4rem;background:white;position: absolute;left: 0;top:3rem;z-index:2;display:flex;align-items:center;justify-content:space-around;box-sizing: border-box;padding: 0 0 0 .5rem;';
                let locateStyle = 'width:50%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align:left;';
                let storeStyle = 'width: 33%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align:left;';
                let sendToStyle = 'width: 17%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align:left;';
                locate.setAttribute("style",locateStyle);
                node.setAttribute("style",nodeStyle);
                RecStore.setAttribute("style",RecStyle);
                RecStore.setAttribute("id",'RecStore');
                store.setAttribute("style",storeStyle);
                sendTo.setAttribute("style",sendToStyle);
                node.setAttribute("id",'zxHomeCover');
                myPopup.appendChild(node);
                myPopup.appendChild(RecStore);
                RecStore.appendChild(sendTo);
                RecStore.appendChild(locate);
                RecStore.appendChild(store);
				//此处使用setTimeOut 是因为改变样式会造成回流 导致动画出不来 所以强制用两个线程
				node.style.display = "block";
				setTimeout(() => {
					node.style.transition = "opacity 0.3s";
					node.style.opacity = "0.5";
				}, 0);
                node.onclick = e => {
                    this.showPop();
                }
			}
		},
		//隐藏遮罩层
		removeCover(){
			if(document.getElementById('zxHomeCover')){
                document.getElementById('zxHomeCover').remove(0);
                document.querySelector('.nav_root').removeChild(document.querySelector("#RecStore"));
			}
        },
        showPop(){
            if(this.getIsShow){
                this.setIsShow(false);
                this.removeCover();
            }else{
                this.setIsShow(true);
                this.appendCover();
            }
        },
        async getStores(){
            var url = window.api.base_host + "/baseStore/getRestStore";
            var params = {
                enterpriseCode: window.api.enterpriseCode
            }
            var config = {
                url: url,
                methods: "GET",
                params
            }
            let res = await axios(config);
            if (res.data.returnCode == 1) {
                this.stores = res.data.data[0];
                this.$store.dispatch('qxz/updateStoreList', res.data.data[0]);
                // this.$store.dispatch('cjy/storeCodeOnChange')
            }
        },
        //判断ios版本
        getIosVersion() {
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
            var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            if (isAndroid) {
                //这个是安卓操作系统
                return false
            }
            if (isIOS) {
        　　　　//这个是ios操作系统
                var ver = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                // ver = parseInt(ver[1], 10);
                var IosVersion = (ver[1] || '0') + (ver[2] || '0') + (ver[3] || '0');
                if(Number(IosVersion) < 935) {
                    return true
                }else {
                    return false
                }
            }
        },
        initScript() {
            //判断如果有script就删掉
			if (document.querySelector("#amap-box")){
                // document.body.removeChild(document.querySelector("#amap-box"));
                this.initMap();
			}else{
                let amapBox = document.createElement("div");
                amapBox.setAttribute("id", "amap-box");
                // this.initMap();
                let script1 = document.createElement("script");
                script1.onload = () => {
                    let script2 = document.createElement("script");
                    script2.onload = () => {
                        this.initMap();
                    }
                    script2.src = "//webapi.amap.com/ui/1.0/main.js";
                    amapBox.insertAdjacentElement("beforeend", script2);
                };
                if(this.getIosVersion()) {
                    script1.src = `https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba`;
                }else {
                    script1.src = `https://webapi.amap.com/maps?v=1.4.6&key=9bfe3d8b8882b7d3e4c23e43d38b18ba`;
                }
                amapBox.insertAdjacentElement("beforeend", script1);
                document.body.appendChild(amapBox);
            }
        },
        initMap(){
            var that = this;
            var addParams = this.$route.query;
            var adderssArr = [];
            function waitMap (){
                if(AMap.Map){
                    keepGoing();
                }else{
                    setTimeout(() => {
                        waitMap();
                    },300)
                }
            }
            waitMap();
            function keepGoing() {
                var map = new AMap.Map('allmap', {
                    resizeEnable: true,
                    zoom: 15,
                    center: [108.383765, 22.813923],
                    scrollWheel : true
                });
                var shop;
                var kmReg = /\d+km/;
                //所有marker的集合，用于地图自适应缩放
                var markerList = [];
                var tenSecond = false;
                var tenTimer;
                function pursue() {
                    if(!JSON.parse(localStorage.getItem("locateIn")), !JSON.parse(localStorage.getItem("locateOut"))) {
                        map.plugin(['AMap.Geolocation'], function() {
                            //给一个定位过程的loading
                            var geolocation = new AMap.Geolocation({
                                enableHighAccuracy: true, //是否使用高精度定位，默认:true
                                timeout: 10000, //超过10秒后停止定位，默认：无穷大
                                maximumAge: 0, //定位结果缓存0毫秒，默认：0
                                convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                                showButton: true, //显示定位按钮，默认：true
                                buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
                                buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                                showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
                                showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
                                panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                                zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
                            });
                            map.addControl(geolocation);
                            geolocation.getCurrentPosition();
                            tenTimer = setTimeout(() => {
                                that.showLocateFailed = true;
                            },11000)
                            //添加定位失败和定位成功的监听事件
                            geolocation.on("complete", async function (result) {
                                //关闭loading效果
                                clearTimeout(tenTimer);
                                tenTimer = null;
                                let lists = [];
                                let obj = {};
                                let Pos = {};
                                if(result.addressComponent){
                                    result.formateAdd = result.addressComponent.city + result.addressComponent.district + result.addressComponent.street + result.addressComponent.streetNumber;
                                }
                                lists.push(result);
                                //不显示定位失败
                                that.showLocateFailed = false;
                                that.locateSpot = lists;
                                let inArea = false;
                                that.polygonList.forEach((item,index) => {
                                    let lnglat = new AMap.LngLat(result.position.lng, result.position.lat);
                                    item.contains(lnglat) ? result.inArea = true : "";
                                }, this)
                                if(result.inArea && result.addressComponent){
                                    obj.province = result.addressComponent.province;
                                    obj.city = result.addressComponent.city || '市辖区';
                                    obj.region = result.addressComponent.district;
                                    obj.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                                    obj.positionlng = result.position.lng;
                                    obj.positionlat = result.position.lat;
                                    obj.addressid = "-1";
                                    Pos.province = result.addressComponent.province;
                                    Pos.city = result.addressComponent.city || '市辖区';
                                    Pos.region = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;
                                    Pos.address = result.formattedAddress;
                                    Pos.positionlng = result.position.lng;
                                    Pos.positionlat = result.position.lat;
                                    Pos.addressid = "-1";
                                    Pos.inArea = true;
                                    localStorage.setItem("locateIn", JSON.stringify(obj));
                                    localStorage.setItem("currentPos", JSON.stringify(Pos));
                                    !that.locationInfo && that.$store.dispatch('qxz/updateLocation', obj);
                                }else if(!result.inArea && result.addressComponent){
                                    obj.address = '不在配送范围内';
                                    obj.province = result.addressComponent.province;
                                    obj.city = result.addressComponent.city;
                                    obj.formateAdd = result.formattedAddress;
                                    obj.positionlng = result.position.lng;
                                    obj.positionlat = result.position.lat;
                                    Pos.address = result.addressComponent.street + result.addressComponent.streetNumber + result.addressComponent.township;;
                                    Pos.province = result.addressComponent.province;
                                    Pos.city = result.addressComponent.city;
                                    Pos.formateAdd = result.formattedAddress;
                                    Pos.positionlng = result.position.lng;
                                    Pos.positionlat = result.position.lat;
                                    Pos.inArea = false;
                                    localStorage.setItem("locateOut", JSON.stringify(obj));
                                    localStorage.setItem("currentPos", JSON.stringify(Pos));
                                    that.$store.dispatch('qxz/updateScopeOut', obj);
                                }
                                localStorage.setItem('poslng', result.position.lng);
                                localStorage.setItem('poslat', result.position.lat);
                                // let cpoint = [];
                                // cpoint.push(result.position.lng);
                                // cpoint.push(result.position.lat);
                                // var maxNearPoi = 3;
                                // if(that.locationInfo){
                                //     var lnglat = new AMap.LngLat(that.locationInfo.positionlng, that.locationInfo.positionlat);
                                // }else{
                                //     var lnglat = new AMap.LngLat(result.position.lng, result.position.lat);
                                // }
                                // var url = window.api.base_host + "/baseStore/getRestStore";
                                // var params = {
                                //     enterpriseCode: window.api.enterpriseCode
                                // }
                                // if(!that.getStoreList.length) {
                                //     await that.getStores();
                                // }
                                // that.stores = that.getStoreList;
                                // let storeList = that.getStoreList;
                                // let Arr = [];
                                // let minDistance;
                                // let minDistanceItem;
                                // storeList.forEach((item, index) => {
                                //     item.positionLng && item.positionLat && Arr.push(item);
                                // },this);
                                // // console.log(Arr,"Arr");
                                // let storeInd = 0;
                                // Arr.forEach((item,index) => {
                                //     let arr = [];
                                //     arr.push(item.positionLng);
                                //     arr.push(item.positionLat)
                                //     var myDistance = Number(lnglat.distance(arr));
                                //     // console.log(myDistance,"myDistance")
                                //     if (index == 0) {
                                //         minDistance = myDistance;
                                //         minDistanceItem = item;
                                //     } else {
                                //         if (minDistance > myDistance) {
                                //             minDistance = myDistance;
                                //             minDistanceItem = item;
                                //             storeInd = index;
                                //         }
                                //     }
                                //     // console.log(minDistance,"minDistance")
                                //     that.minDistanceItem = minDistanceItem;
                                //     // console.log(that.minDistanceItem, "minDistanceItem")
                                // },this);
                                // localStorage.setItem('storeName', minDistanceItem.storeName);
                                // localStorage.setItem("storeLng", minDistanceItem.positionLng);
                                // localStorage.setItem("storeLat", minDistanceItem.positionLat);
                                // localStorage.setItem("storeCode", Arr[storeInd].storeCode);
                                // localStorage.setItem("storeId", Arr[storeInd].storeId);
                                // window.api.storeCode = Arr[storeInd].storeCode;
                                // if(that.storeCode == Arr[storeInd].storeCode){

                                // }else{
                                    // that.storeCode = Arr[storeInd].storeCode;
                                    // that.$store.dispatch('cjy/storeCodeOnChange')
                                // }
                            });
                            geolocation.on("error", function (err) {
                                that.showLocateFailed = true;
                                if(that.stores){
                                    that.stores.forEach((item,index) => {
                                        if(item.storeCode == localStorage.getItem("storeCode")){
                                            that.defaultStore = item.storeName;
                                            // console.log(item,"failed")
                                            localStorage.setItem('storeName', item.storeName);
                                            localStorage.setItem("storeLng", item.positionLng);
                                            localStorage.setItem("storeLat", item.positionLat);
                                        }
                                    },this)
                                }
                            });
                        });
                    }
                    console.log('that.getStoreList',that.getStoreList)
                    that.getStoreList.map(ele => {
                        if(ele.storeCode == api.storeCode) {
                            localStorage.setItem('storeName', ele.storeName);
                            localStorage.setItem("storeLng", ele.positionLng);
                            localStorage.setItem("storeLat", ele.positionLat);
                            localStorage.setItem("storeCode", ele.storeCode);
                            localStorage.setItem("storeId", ele.storeId);
                        }
                    })
                }

                (function () {
                    var isShow = false;
                    //请求配送范围的经纬度数组
                    let url = api.customer_host + "/address/getTMS";
                    axios.get(url,{
                            "longitudeandlatitude":""
                        })
                        .then(function (res) {
                            that.polygonList = [];
                            //门店配送范围
                            let array = new Array();
                            for(let item of res.data.data[0]){
                                let Arr = new Array();
                                for(let it of JSON.parse(item.longitudeandlatitude)){
                                    let arr = new Array();
                                    arr[0] = it.a;
                                    arr[1] = it.b;
                                    Arr.push(arr);
                                }
                                item.deptid == localStorage.getItem("storeId") && array.push(Arr);
                            }
                            //多边形覆盖物节点坐标数组
                            for (let item of array){
                                var polygon = new AMap.Polygon({
                                    map: map,
                                    path: item,//设置多边形边界路径
                                    strokeColor: "red", //线颜色
                                    strokeOpacity: 0.2, //线透明度
                                    strokeWeight: 3,    //线宽
                                    fillColor: "red", //填充色
                                    fillOpacity: 0.35//填充透明度
                                });
                                polygon.setMap(map);
                                that.polygonList.push(polygon);
                            }
                            pursue();
                            // console.log(that.polygonList,"polygonList")
                        })
                        .catch(function (res) {
                            //console.log(res);
                        });
                })();
            }
        },
    },
}
</script>
<style scoped>
    .locate{
        display: flex;
        width: 100%;
        height: 100%;
        align-items: center;
        justify-content: space-between;
    }
    .midPart{
        width: 58%;
        height: 50%;
        border: 1px solid #E9E9E9;
        border-radius: .1rem;
        /* display: flex;
        align-items: center;
        justify-content: space-between; */
    }
    .midPart p{
        width: 80%;
        height: 100%;
        line-height: 1.5rem;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        float: left;
    }
    .midPart div{
        height: 100%;
        float: right;
    }
    .arrow{
        transform: rotate(180deg);
    }
    .contentPopup {
        /*height: 6.6rem;*/
        max-height: 70vh;
        position: absolute;
        top: 3rem;
        left: 0rem;
        width: 100%;
        transition: 0.3s;
        overflow-y: scroll;
        z-index: 2;
    }

    .locatePic{
        font-size: .8rem;
    }

    .content-heidden {
        height: 0;
    }
</style>
